package com.ruoyi.sale.controller;

import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.sale.domain.ErpGoodss;
import com.ruoyi.sale.domain.WarehouseDept;
import org.apache.ibatis.annotations.Param;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.sale.domain.ErpOrder;
import com.ruoyi.sale.service.IErpOrderService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 订单Controller
 *
 * @author ruoyi
 * @date 2025-03-10
 */
@RestController
@RequestMapping("/xiaoshou/sale")
public class ErpOrderController extends BaseController
{
    @Autowired
    private IErpOrderService erpOrderService;

    /**
     * 查询订单列表
     */
    @PreAuthorize("@ss.hasPermi('xiaoshou:sale:list')")
    @GetMapping("/list")
    public TableDataInfo list(ErpOrder erpOrder)
    {
        startPage();
        List<ErpOrder> list = erpOrderService.selectErpOrderList(erpOrder);
        return getDataTable(list);
    }

    /**
     * 导出订单列表
     */
    @PreAuthorize("@ss.hasPermi('xiaoshou:sale:export')")
    @Log(title = "订单", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, ErpOrder erpOrder)
    {
        List<ErpOrder> list = erpOrderService.selectErpOrderList(erpOrder);
        ExcelUtil<ErpOrder> util = new ExcelUtil<ErpOrder>(ErpOrder.class);
        util.exportExcel(response, list, "订单数据");
    }

    /**
     * 获取订单详细信息
     */
    @PreAuthorize("@ss.hasPermi('xiaoshou:sale:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") int id)
    {
        return success(erpOrderService.selectErpOrderById(id));
    }

    /**
     * 新增订单
     */
    @PreAuthorize("@ss.hasPermi('xiaoshou:sale:add')")
    @Log(title = "订单", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody ErpOrder erpOrder)
    {
        int result = erpOrderService.insertErpOrder(erpOrder);
        if (result > 0) {
            // 返回新增的完整订单数据
            ErpOrder newOrder = erpOrderService.selectErpOrderById(erpOrder.getId());
            return AjaxResult.success(newOrder); // 确保返回完整数据
        }
        return toAjax(erpOrderService.insertErpOrder(erpOrder));
    }

    /**
     * 修改订单
     */
    @PreAuthorize("@ss.hasPermi('xiaoshou:sale:edit')")
    @Log(title = "订单", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody ErpOrder erpOrder)
    {
        return toAjax(erpOrderService.updateErpOrder(erpOrder));
    }

    /**
     * 删除订单
     */
    @PreAuthorize("@ss.hasPermi('xiaoshou:sale:remove')")
    @Log(title = "订单", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable int[] ids)
    {
        return toAjax(erpOrderService.deleteErpOrderByIds(ids));
    }



    @GetMapping("/warehouseDeptList")
    public AjaxResult getWarehouseDeptList() {
        List<WarehouseDept> list = erpOrderService.selectWarehouseDeptList();
        return success(list);
    }

    /**
     *
     * 审核订单
     */
    @PreAuthorize("@ss.hasPermi('xiaoshou:sale:audit')")
    @Log(title = "订单", businessType = BusinessType.UPDATE)
    @PutMapping("/audit/{id}")
    public AjaxResult audit(@PathVariable int id, @RequestParam String action) {
        if ("approve".equals(action)) {
            return toAjax(erpOrderService.approveErpOrder(id));
        } else if ("reject".equals(action)) {
            return toAjax(erpOrderService.rejectErpOrder(id));
        }
        return AjaxResult.error("无效操作");
    }

    /**
     * 出库订单
     */
    @PreAuthorize("@ss.hasPermi('xiaoshou:sale:outbound')")
    @Log(title = "订单", businessType = BusinessType.UPDATE)
    @PutMapping("/outbound/{id}")
    public AjaxResult outbound(@PathVariable int id) {
        return toAjax(erpOrderService.outboundErpOrder(id));
    }

    /**
     * 设为已支付
     */
    @PreAuthorize("@ss.hasPermi('xiaoshou:sale:pay')")
    @Log(title = "订单", businessType = BusinessType.UPDATE)
    @PutMapping("/pay/{id}")
    public AjaxResult pay(@PathVariable int id) {

        return toAjax(erpOrderService.payErpOrder(id));
    }

    @GetMapping("/goodsList")
    public TableDataInfo goodsList() {
        startPage();
        List<ErpGoodss> list = erpOrderService.selectErpGoodsList(null);
        return getDataTable(list);
    }

    @PostMapping("/updateStock")
    @PreAuthorize("@ss.hasPermi('xiaoshou:sale:edit')")
    public AjaxResult updateStock(@RequestBody Map<String, Object> params) {
        Long productId = Long.parseLong(params.get("productId").toString());
        Long warehouseId = Long.parseLong(params.get("warehouseId").toString());
        Integer quantity = Integer.parseInt(params.get("quantity").toString());

        int result = erpOrderService.updateProductStock(productId, warehouseId, quantity);
        return result > 0 ? AjaxResult.success() : AjaxResult.error("更新库存失败");
    }

    @PreAuthorize("@ss.hasPermi('xiaoshou:sale:query')")
    @GetMapping("/goods/{orderId}")
    public AjaxResult getOrderGoods(@PathVariable Long orderId) {
        return success(erpOrderService.getOrderGoodsByOrderId(orderId));
    }


    public interface ErpOrderMapper {
        /**
         * 根据仓库ID查询商品库存
         * @param warehouseId 仓库ID
         * @return 商品列表（含库存数量）
         */
        List<ErpGoodss> selectGoodsStockByWarehouse(@Param("warehouseId") Long warehouseId);
    }

    @GetMapping("/order/goods/{orderId}")
    public AjaxResult getOrderGoodsByOrderId(@PathVariable Long orderId) {
        List<ErpGoodss> goodsList = erpOrderService.getOrderGoodsByOrderId(orderId);
        // 确保返回的数据中quantity不为0
        goodsList.forEach(item -> {
            if(item.getCountNum() == 0) {
                item.setCountNum(1); // 设置默认值或从数据库重新查询
            }
        });
        return AjaxResult.success(goodsList);
    }

}

